<template>
  <div class="notice-management">
    <h1>公告管理</h1>

    <!-- 轮播图表格 (type=1) -->
    <div class="table-section">
      <h2>轮播图管理</h2>
      
      <div class="table-controls">
        <el-input
          v-model="carouselSearch"
          placeholder="搜索轮播标题或内容"
          clearable
          size="small"
          class="search-input"
          @clear="handleCarouselSearch"
          @keyup.enter.native="handleCarouselSearch"
        >
          <template #append>
            <el-button icon="Search" size="small" @click="handleCarouselSearch" />
          </template>
        </el-input>
      </div>
      
      <el-table
        :data="filteredCarouselData"
        border
        stripe
        size="small"
        :loading="loading"
        highlight-current-row
        @row-click="handleCarouselRowClick"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="noticeId" label="ID" width="80" align="center" />
        <el-table-column prop="title" label="标题" min-width="200">
          <template #default="scope">
            <span class="notice-title">{{ scope.row.title }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="内容" min-width="200">
          <template #default="scope">
            <span class="notice-title">{{ scope.row.text }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="imageCount" label="图片数量" width="100" align="center">
          <template #default="scope">
            {{ scope.row.imageArray.length }}
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="180" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center">
          <template #default="scope">
            <el-button
              icon="Edit"
              size="mini"
              @click="handleEditCarousel(scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 公告表格 (type=2) -->
       <div class="table-section">
      <h2>公告管理</h2>
      
      <div class="table-controls">
        <el-input
          v-model="carouselSearch"
          placeholder="搜索轮播标题或内容"
          clearable
          size="small"
          class="search-input"
          @clear="handleNoticeSearch"
          @keyup.enter.native="handleNoticeSearch"
        >
          <template #append>
            <el-button icon="Search" size="small" @click="handleNoticeSearch" />
          </template>
        </el-input>
        
      </div>
      
      <el-table
        :data="filteredNoticeData"
        border
        stripe
        size="small"
        :loading="loading"
        highlight-current-row
        @row-click="handleNoticeRowClick"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="noticeId" label="ID" width="80" align="center" />
        <el-table-column prop="title" label="标题" min-width="200">
          <template #default="scope">
            <span class="notice-title">{{ scope.row.title }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="内容" min-width="200">
          <template #default="scope">
            <span class="notice-title">{{ scope.row.text }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="imageCount" label="图片数量" width="100" align="center">
          <template #default="scope">
            {{ scope.row.imageArray.length }}
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="180" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center">
          <template #default="scope">
            <el-button
              icon="Edit"
              size="mini"
              @click="handleEditNotice(scope.row)"
            />
          </template>
        </el-table-column>
        </el-table>
      </div>

      <!-- 编辑弹窗 -->
      <el-dialog v-model="editDialogVisible" title="编辑公告/轮播图" width="600px" :close-on-click-modal="false">
        <el-form :model="editForm" label-width="100px">
          <el-form-item label="ID">
            <el-input v-model="editForm.noticeId" disabled />
          </el-form-item>
          <el-form-item label="类型">
            <el-tag type="info">{{ editForm.type === 1 ? '轮播图' : '公告' }}</el-tag>
          </el-form-item>
          <el-form-item label="标题">
            <el-input v-model="editForm.title" placeholder="请输入标题" />
          </el-form-item>
          <el-form-item label="内容">
            <el-input type="textarea" :rows="4" v-model="editForm.text" placeholder="请输入内容" />
          </el-form-item>
          <el-form-item label="图片">
            <el-upload
              class="image-uploader"
              list-type="picture-card"
              :file-list="uploadFileList"
              :auto-upload="false"
              :on-change="handleUploadChange"
              :on-remove="handleUploadRemove"
              :on-preview="handlePictureCardPreview"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
            <el-dialog v-model="previewVisible" width="50%">
              <img :src="previewImage" style="width: 100%;" />
            </el-dialog>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="editDialogVisible = false" :disabled="isSubmitting">取消</el-button>
          <el-button type="primary" @click="submitEdit" :loading="isSubmitting">保存</el-button>
        </template>
      </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { Plus, Search, Edit } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { getAllNotice,updateNotice,updateAvatar } from '@/api/notice';

// 状态管理
const notices = ref([]);
const loading = ref(false);
const carouselSearch = ref('');
const noticeSearch = ref('');

// 过滤后的轮播图数据
const filteredCarouselData = computed(() => {
  return notices.value
    .filter(item => item.type === 1)
    .filter(item => {
      const searchStr = carouselSearch.value.toLowerCase();
      return (
        item.title.toLowerCase().includes(searchStr) ||
        item.text.toLowerCase().includes(searchStr)
      );
    });
});

// 过滤后的公告数据
const filteredNoticeData = computed(() => {
  return notices.value
    .filter(item => item.type === 2)
    .filter(item => {
      const searchStr = noticeSearch.value.toLowerCase();
      return (
        item.title.toLowerCase().includes(searchStr) ||
        item.text.toLowerCase().includes(searchStr)
      );
    });
});

// 获取公告数据
const fetchNotices = async () => {
  loading.value = true;
  try {
    notices.value = await getAllNotice();
    console.log('获取到的公告数据:', notices.value);
  } catch (error) {
    ElMessage.error('获取公告数据失败，请重试');
    console.error('获取公告失败：', error);
  } finally {
    loading.value = false;
  }
};

// 日期格式化
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};

// 搜索方法
const handleCarouselSearch = () => {
  console.log('轮播图搜索:', carouselSearch.value);
};

const handleNoticeSearch = () => {
  console.log('公告搜索:', noticeSearch.value);
};

// 表格操作方法
const handleCarouselRowClick = (row) => {
  console.log('点击了轮播图行:', row);
};

const handleNoticeRowClick = (row) => {
  console.log('点击了公告行:', row);
};

const handleAddCarousel = () => {
  ElMessage.info('打开新增轮播图对话框');
  // 实际应用中这里会打开新增轮播图表单对话框
};

const handleAddNotice = () => {
  ElMessage.info('打开新增公告对话框');
  // 实际应用中这里会打开新增公告表单对话框
};

const handleEditCarousel = (row) => {
  openEditDialog(row);
};

const handleEditNotice = (row) => {
  openEditDialog(row);
};

// 初始化加载数据
onMounted(() => {
  fetchNotices();
});

// 编辑弹窗相关逻辑
const editDialogVisible = ref(false);
const isSubmitting = ref(false);
const editForm = ref({
  noticeId: null,
  title: '',
  text: '',
  type: 1,
  imageArray: [],
  images: ''
});
// 上传相关状态
const uploadFileList = ref([]);
const previewImage = ref('');
const previewVisible = ref(false);

const openEditDialog = (row) => {
  // 优先使用后端规范字段 images（逗号分隔字符串），若为空再回退 imageArray
  let arrayFromRow = normalizeImageArray(row.images || '');
  if ((!arrayFromRow || arrayFromRow.length === 0) && Array.isArray(row.imageArray)) {
    arrayFromRow = row.imageArray;
  }

  editForm.value = {
    noticeId: row.noticeId,
    title: row.title || '',
    text: row.text || '',
    type: row.type,
    imageArray: arrayFromRow,
    images: (arrayFromRow || []).join(',') || null
  };

  uploadFileList.value = (arrayFromRow || []).map((url, idx) => ({ name: `图片${idx + 1}` , url }));
  editForm.value.imageArray = arrayFromRow || [];
  editDialogVisible.value = true;
};

const submitEdit = async () => {
  if (!editForm.value.noticeId) {
    ElMessage.error('缺少公告ID，无法保存');
    return;
  }

  isSubmitting.value = true;
  try {
    const imagesStr = (editForm.value.imageArray || [])
      .map(s => String(s).trim())
      .filter(Boolean)
      .join(',');
    const payload = {
      noticeId: editForm.value.noticeId,
      title: editForm.value.title,
      text: editForm.value.text,
      type: editForm.value.type,
      images: imagesStr && imagesStr.length ? imagesStr : null
    };
    await updateNotice(payload);
    ElMessage.success('保存成功');
    await fetchNotices();
    resetEditState();
    editDialogVisible.value = false;
  } catch (error) {
    console.error('保存失败：', error);
    ElMessage.error('保存失败，请重试');
  } finally {
    isSubmitting.value = false;
  }
};

const resetEditState = () => {
  editForm.value = {
    noticeId: null,
    title: '',
    text: '',
    type: 1,
    imageArray: [],
    images: ''
  };
  uploadFileList.value = [];
  previewImage.value = '';
  previewVisible.value = false;
};

function normalizeImageArray(str) {
  if (!str) return [];
  return String(str)
    .split(/[,\n]/)
    .map(s => s.trim())
    .filter(s => s.length > 0);
}

// 上传事件处理
const handleUploadChange = async (file, fileList) => {
  // 更新展示列表（先展示本地预览，成功后替换为远端URL）
  uploadFileList.value = fileList;

  // 如果是新选择的文件，调用后端上传接口
  if (file && file.raw) {
    const url = await updateAvatar(file.raw);
    if (!url) {
      ElMessage.error('图片上传失败');
      // 失败则移除该文件
      uploadFileList.value = (uploadFileList.value || []).filter(f => f !== file);
    } else {
      // 用后端返回的远端URL替换
      file.url = url;
    }
  }

  // 同步编辑数据：数组与字符串
  editForm.value.imageArray = (uploadFileList.value || [])
    .map(f => f.url || (typeof f.response === 'string' ? f.response : f.response?.url))
    .filter(Boolean);
  editForm.value.images = (editForm.value.imageArray || []).length
    ? (editForm.value.imageArray || []).join(',')
    : null;
};

const handleUploadRemove = (file, fileList) => {
  uploadFileList.value = fileList;
  editForm.value.imageArray = (fileList || [])
    .map(f => f.url || (typeof f.response === 'string' ? f.response : f.response?.url))
    .filter(Boolean);
  editForm.value.images = (editForm.value.imageArray || []).length
    ? (editForm.value.imageArray || []).join(',')
    : null;
};

const handlePictureCardPreview = (file) => {
  previewImage.value = file.url || '';
  if (previewImage.value) {
    previewVisible.value = true;
  }
};
</script>

<style scoped>
.notice-management {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  min-height: calc(100vh - 40px);
}

.table-section {
  margin-bottom: 30px;
  padding: 15px;
  border: 1px solid #eaeaea;
  border-radius: 4px;
}

.table-section h2 {
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 18px;
  color: #333;
  border-bottom: 1px solid #eaeaea;
  padding-bottom: 10px;
}

.table-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 15px 0;
}

.search-input {
  width: 300px;
}

.notice-title {
  /* 强制显示一行 */
  white-space: nowrap;
  /* 超出容器部分隐藏 */
  overflow: hidden;
  /* 用省略号替代超出部分 */
  text-overflow: ellipsis;
  /* 确保元素有明确的宽度限制（继承父容器宽度） */
  display: inline-block;
  width: 100%;
}

.notice-title:hover {
  color: #409eff;
  cursor: pointer;
}

.text-summary {
  color: #666;
  line-height: 1.5;
}

/* 表格行悬停效果优化 */
::v-deep .el-table__row:hover > td {
  background-color: #f5f7fa !important;
}

/* 选中行样式优化 */
::v-deep .el-table__row.current-row > td {
  background-color: #e6f7ff !important;
}

.image-preview-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 8px;
}

.image-preview-item {
  width: 80px;
  height: 60px;
  overflow: hidden;
  border: 1px solid #eee;
  border-radius: 4px;
}
</style>